//
//  WXPBankCardVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/3/10.
//
//

#import "WXPBankCardVC.h"
#import "WXPBankCardCell.h"
#import "WXPInputNewCardInfoVC.h"
#import "WXPInputOldCardInfoVC.h"
#import "WXPWebLivenessVC.h"
#import "WXPFaceCameraVC.h"
#import "WXPLivenessFailView.h"




@interface WXPBankCardVC ()

@property (nonatomic, strong) WXPNavView * navView;
@property (nonatomic, strong) UIView * blankPageView;
@property (nonatomic, strong) WXPCommonAgreementView * agreementView;
@property (nonatomic, strong) WXPLivenessFailView * livenessFailView;

@end

@implementation WXPBankCardVC

#pragma mark - lazy
- (WXPNavView *)navView{
    if (_navView == nil) {
        _navView = [WXPNavView  new];
        [_navView resetViewWithTitle:@"Cuenta bancaria"];
        _navView.leftTop = XY(0, 0);
    }
    return  _navView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (UIView *)blankPageView{
    if (_blankPageView == nil) {
        _blankPageView = [UIView  new];
        _blankPageView.backgroundColor = [UIColor clearColor];
        _blankPageView.widthHeight = XY(SCREEN_WIDTH, 0);
        _blankPageView.leftTop = XY(0, 0);
        UIImageView * img = [UIImageView new];
        img.image = [UIImage imageNamed:@"icon-list-nodata"];
        img.widthHeight = XY(Ratio(241), Ratio(240));
        img.centerXTop = XY(_blankPageView.width/2, Ratio(60));
        [_blankPageView addSubview:img];
        UILabel * label = [UILabel new];
        [GlobalMethod setLabel:label widthLimit:0 numLines:0 lineSpace:5 isBold:false fontNum:12 textColor:COLOR_CONTENT aligent:NSTextAlignmentCenter text:@"No hay más contenido disponible en este\nmomento, continúe solicitando más préstamos." bgColor:[UIColor clearColor]];
        label.centerXTop = XY(img.centerX, img.bottom+Ratio(25));
        [_blankPageView addSubview:label];
        _blankPageView.height = label.bottom;
    }
    return  _blankPageView;
}
- (WXPLivenessFailView *)livenessFailView
{
    if (_livenessFailView == nil) {
        _livenessFailView = [WXPLivenessFailView  new];
    }
    return  _livenessFailView;
}

#pragma mark - viewDidLoad
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Bankcard action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    
    [self requestList];
    [self addRefresh];
}

- (void)addRefresh{
    [self addRefreshHeader];
}

- (void)configUI{
    self.view.backgroundColor = COLOR_BACKGROUND;
    self.viewBG.backgroundColor = COLOR_BACKGROUND;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[WXPBankCardCell class] forCellReuseIdentifier:NSStringFromClass([WXPBankCardCell class])];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    self.tableView.height = self.agreementView.top-10-self.navView.bottom-10;
    self.tableView.top = self.navView.bottom+10;
    
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.aryDatas.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WXPBankCardCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WXPBankCardCell class]) forIndexPath:indexPath];
    [cell resetCellWithModel:self.aryDatas[indexPath.row]];
    WEAKSELF
    cell.blockEditBank = ^(ModelBankCard * model) {
        [GlobalMethod hitPointWithPageName:KEY_Bankcard action:KEY_Click extInfo:nil];
        [weakSelf requestBankCardSteps:model];
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [WXPBankCardCell getHeight:self.aryDatas[indexPath.row] className:@"" selectorName:@"resetCellWithModel:"];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return isAry(self.aryDatas)?[UIView new]:self.blankPageView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return isAry(self.aryDatas)?CGFLOAT_MIN:self.blankPageView.height;;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

#pragma mark -  跳转事件
// 跳转去活体拍照
- (void)jumpToLivenessTakePhotoWithModel:(ModelBankCard *)model{
    WEAKSELF
    WXPFaceCameraVC * vc = [WXPFaceCameraVC new];
    vc.liveType = 3;
    vc.livenChannelEnum = KEY_SILENCE_LIVENESS;
    vc.liveTypeEnum = KEY_MODIFY_BANK_CARD_LIVE;
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        //检查修改银行卡活体接口
        [weakSelf requestCheckModifyBankCardLiveWithPhotoName:photoName livenessId:livenessId model:model livenChannel:KEY_SILENCE_LIVENESS];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg":errorStr}];
        [weakSelf.view addSubview:weakSelf.livenessFailView];
    };
    [Global_Nav pushViewController:vc animated:true];
}

// 跳转去H5活体拍照
- (void)jumpToLivenessH5WithModel:(ModelBankCard *)model{
    WXPWebLivenessVC * vc = [WXPWebLivenessVC new];
    vc.liveTypeEnum = KEY_MODIFY_BANK_CARD_LIVE;
    WEAKSELF
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        //检查修改银行卡活体接口
        [weakSelf requestCheckModifyBankCardLiveWithPhotoName:photoName livenessId:livenessId model:model livenChannel:KEY_CLOUDUN_H5_V3];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg":errorStr}];
    };
    [Global_Nav pushViewController:vc animated:true];
}

#pragma mark - request
- (void)requestList{
    [RequestApi requestBankCardListWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        if (self.isRemoveAll) {
            [self.aryDatas removeAllObjects];
        }
        
        NSArray * aryResponse = [GlobalMethod exchangeDic:response toAryWithModelName:@"ModelBankCard"];
        if(aryResponse.count < 10){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        self.pageNum++;
        if (isAry(aryResponse)) {
            [self.aryDatas addObjectsFromArray: aryResponse];
        }else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 获取修改银行卡认证步骤接口
///api/auth/get-modify_steps
- (void)requestBankCardSteps:(ModelBankCard *)model{
    [RequestApi requestAuthModifyStepsWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        NSArray * stepAry = [response arrayValueForKey:KEY_step];
        BOOL isCheckOrigin = [stepAry containsObject: @"check_origin"];
        BOOL isLiveness = [stepAry containsObject: @"liveness"];
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_Bankcard action:KEY_Get_Config extInfo:@{@"checkBankCard":isCheckOrigin?@"true":@"false", @"liveness":isLiveness?@"true":@"false"}];
        
#if DEBUG
//        isCheckOrigin = true;
//        isLiveness = true;
#endif
        
        // 两个都不包含，直接跳转到 新卡信息输入页面
        if(isCheckOrigin == false && isLiveness == false){
            WXPInputNewCardInfoVC * vc = [WXPInputNewCardInfoVC new];
            vc.modelBankCard = model;
            [Global_Nav pushViewController:vc animated:true];
        }

        // 两个都包含，先做银行卡校验，银行卡校验成功再做活体校验
        if(isCheckOrigin && isLiveness){
            WXPInputOldCardInfoVC * vc = [WXPInputOldCardInfoVC new];
            vc.bankCardModel = model;
            vc.needLiveness = isLiveness;
            [Global_Nav pushViewController:vc animated:true];
        }

        // 需要 银行卡校验，不需要 活体
        if(isCheckOrigin && isLiveness == false){
            WXPInputOldCardInfoVC * vc = [WXPInputOldCardInfoVC new];
            vc.bankCardModel = model;
            vc.needLiveness = false;
            [Global_Nav pushViewController:vc animated:true];
        }

        // 需要 活体，不需要 银行卡校验
        if(isCheckOrigin == false && isLiveness){
            // 检查是否可以做某项授权接口
            [self requestAuthCheckWithAuthTypeWithModel:model];
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 检查用户是否可以做某项授权接口
- (void)requestAuthCheckWithAuthTypeWithModel:(ModelBankCard *)model{
    [RequestApi requestCheckUserCanAuthWithType:KEY_LIVENESS phone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        if([response boolValueForKey:KEY_checkResult]){
            // true，调用 获取活体渠道 - 先验证相机权限
            WEAKSELF
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                [GlobalMethod mainQueueBlock:^{
                    if (granted){
                        [weakSelf requestAuthLivenConfigWithModel:model];
                    }
                }];
            }];
        }else{
            // 当接口返回‘false’时，弹窗提示
            [GlobalMethod showAlert:@"Lo sentimos. Aún no es la fecha del evento"];
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 获取活体渠道接口
- (void)requestAuthLivenConfigWithModel:(ModelBankCard *)model{
    [RequestApi requestNewAuthLivenConfigWithPhone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if(isStr([response stringValueForKey:KEY_SILENCE_LIVENESS])){
            [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"SILENCE_LIVENESS"}];
            // SILENCE_LIVENESS不为null：跳转静默活体页开始做静默活体拍照
            //[GlobalMethod userBehaviorRecordWithPageName:@"ChangeBankFacial" action:@"Liveness_Do" extInfo:@{@"livenChannel": @"SILENCE_LIVENESS"}];
            [self jumpToLivenessTakePhotoWithModel:model];
        }else if(isStr([response stringValueForKey:KEY_CLOUDUN_H5_V3])){
            [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"KEY_CLOUDUN_H5_V3"}];
            // CLOUDUN_H5_V3不为null：跳转LivenessH5 SDK-2活体进行识别
            //[GlobalMethod userBehaviorRecordWithPageName:@"ChangeBankFacial" action:@"Liveness_Do" extInfo:@{@"livenChannel": @"CLOUDUN_H5_V3"}];
            [self jumpToLivenessH5WithModel:model];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 检查修改银行卡活体接口
- (void)requestCheckModifyBankCardLiveWithPhotoName:(NSString *)photoName livenessId:(NSString *)livenessId model:(ModelBankCard *)model livenChannel:(NSString *)livenChannel{
    [RequestApi requestCheckModifyBankCardLiveWithLivenChannelEnum:livenChannel livenessId:livenessId livenessImg:photoName delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Success extInfo:nil];
        WXPInputNewCardInfoVC * vc = [WXPInputNewCardInfoVC new];
        vc.modelBankCard = model;
        [Global_Nav pushViewController:vc animated:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"livenessId":livenessId, @"errorMsg": errorStr}];
    }];
}


@end
